#!/bin/bash -x

kata_coco_top_dir="$HOME/workspace/CoCo"

deployment_repo_url="https://gitee.com/hanliyang-kata-coco/deployment.git"
deployment_repo_branch="master"
deployment_repo_dir="${kata_coco_top_dir}/deployment"

if [ ! -e ${kata_coco_top_dir} ]; then
  mkdir -p ${kata_coco_top_dir}
fi

download_deployment_repo () {
  sudo apt install -y git

  if [ ! -e ${deployment_repo_dir} ]; then
    git clone ${deployment_repo_url} \
      -b ${deployment_repo_branch} \
      ${deployment_repo_dir}
  fi
}

download_deployment_repo


source $HOME/.profile

install_basic_deps () {
  echo "Install basic deps"
  sudo apt install -y curl
}

install_basic_deps

# Install go
install_go_lang () {
  go_version="1.22.2"
  command go version > /dev/null
  if [ $? -ne 0 ]; then
    echo "Install go (${go_version})"
    if [ ! -e "/tmp/go${go_version}.linux-amd64.tar.gz" ]; then
      wget -O /tmp/go${go_version}.linux-amd64.tar.gz \
        https://golang.org/dl/go${go_version}.linux-amd64.tar.gz
    fi
    sudo tar -C /usr/local -xzf /tmp/go${go_version}.linux-amd64.tar.gz
    sed -i '$aexport PATH=$PATH:/usr/local/go/bin' ~/.profile
  fi
}

install_go_lang

# Install rust
install_rustc () {
  rustc_version="1.75.0"
  command rustc --version > /dev/null
  if [ $? -ne 0 ]; then
    mkdir $HOME/.cargo/ || true
    cat > $HOME/.cargo/config.toml <<EOF
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"

# 替换成你偏好的镜像源
replace-with = 'tuna'

# 清华大学
[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"
EOF
# 
# # 中国科学技术大学
# [source.ustc]
# registry = "git://mirrors.ustc.edu.cn/crates.io-index"
# 
# # 上海交通大学
# [source.sjtu]
# registry = "https://mirrors.sjtug.sjtu.edu.cn/git/crates.io-index"
# 
# # rustcc社区
# [source.rustcc]
# registry = "git://crates.rustcc.cn/crates.io-index"
# EOF

    export RUSTUP_DIST_SERVER="https://rsproxy.cn"
    export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup"

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && \
      source $HOME/.cargo/env && \
      rustc --version && \
      rustup install ${rustc_version} && \
      rustup default ${rustc_version} && \
      rustc --version
  fi
}

install_rustc

install_docker () {
  echo "Install docker"

  command docker help > /dev/null
  if [ $? -ne 0 ]; then
    curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | \
      sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable" | \
      sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
    sudo apt update
    sudo apt install -y docker-ce docker-ce-cli containerd.io

    sudo usermod -aG docker $USER
    sudo systemctl daemon-reload && sudo systemctl restart docker
  fi
}

install_docker
